package com.cbj.db_work.controller;


import com.cbj.db_work.common.result.R;
import com.cbj.db_work.common.utils.Base64;
import com.cbj.db_work.entity.Test;
import com.cbj.db_work.service.TestService;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cbj
 * @since 2021-08-10
 */
@RestController
@RequestMapping("/db_work/test")
public class TestController {
    @Autowired
    TestService testService;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @GetMapping
    public R test(){
        Test test = new Test();
        testService.save(test);
        Test byId = testService.getById("1425115164377739266");
        System.out.println(byId);
        return R.ok();
    }



        /**
         * 生成验证码
         */
        @GetMapping("/captchaImage")
        public R getCode(HttpServletResponse response) throws IOException
        {
            // 保存验证码信息
            String uuid = UUID.randomUUID().toString();
            String verifyKey = "captcha_codes:" + uuid;

            String capStr = null, code = null;
            BufferedImage image = null;

            // 生成验证码

                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                image = captchaProducerMath.createImage(capStr);


            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            try
            {
                ImageIO.write(image, "jpg", os);
            }
            catch (IOException e)
            {
                return R.error();
            }
            R ajax = R.ok().data("img",Base64.encode(os.toByteArray()));
            return ajax;
        }
    }




